/**
 * Created by daichaoren on 16-8-24.
 */

var logTab=document.getElementById("logTab");
var errorTab=document.getElementById("errorTab");
var logarea=document.getElementById("logarea");
var errorarea=document.getElementById("errorarea");

function showLog(text) {
    logTab.className="add-border-li";
    errorTab.className="";
    logarea.className="change-box chang-show";
    errorarea.className="change-box";
    if (text) logarea.textContent =text;
}
logTab.onclick=function(){
    showLog();
}

function showError(text) {
    errorTab.className="add-border-li";
    logTab.className="";
    errorarea.className="change-box chang-show";
    logarea.className="change-box";

    if (text)errorarea.innerHTML = text;
}

errorTab.onclick=function(){
   showError();
}
function chart(total_returns_list, benchmark_return_list) {
    Highcharts.setOptions({
    lang:{
           contextButtonTitle:"图表导出菜单",
           decimalPoint:".",
           downloadJPEG:"下载JPEG图片",
           downloadPDF:"下载PDF文件",
           downloadPNG:"下载PNG文件",
           downloadSVG:"下载SVG文件",
           drillUpText:"返回 {series.name}",
           loading:"加载中",
           months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
           noData:"没有数据",
           numericSymbols: [ "千" , "兆" , "G" , "T" , "P" , "E"],
           printChart:"打印图表",
           resetZoom:"恢复缩放",
           resetZoomTitle:"恢复图表",
           shortMonths: [ "一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
           thousandsSep:",",
           weekdays: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六","星期天"],
           rangeSelectorZoom:'缩放'
        }
    });

    $('#backTestChart').highcharts('StockChart', {
        rangeSelector: {
            selected: 2,
            buttons: [{//定义一组buttons,下标从0开始
                    type: 'week',
                    count: 1,
                    text: '1周'
                },
                {
                    type: 'month',
                    count: 1,
                    text: '1月'
                },
                {
                    type: 'month',
                    count: 3,
                    text: '3月'
                },
                {
                    type: 'month',
                    count: 6,
                    text: '6月'
                },
                {
                    type: 'year',
                    count: 1,
                    text: '1年'
                },
                {
                    type: 'all',
                    text: '全部'
                }]
        },
        credits: {
             enabled:false
        },
         yAxis: {
            minorTickInterval: "auto",
				minorTickLength: 10,
				labels: {
					align: "right",
					format: "{value}%",
					x: -3
				},
				opposite: !0,
				height: "100%",
				lineWidth: 0,
				plotLines: [{
					value: 0,
					width: 1,
					color: "#808080"
				}]

         },
        tooltip: {
             dateTimeLabelFormats: {
					second: "%Y-%m-%d %H:%M:%S",
					minute: "%Y-%m-%d %H:%M",
					hour: "%Y-%m-%d %H:%M",
					day: "%Y-%m-%d",
					week: "%Y-%m-%d",
					month: "%Y-%m",
					year: "%Y"
				},
            pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}%</b><br/>',
            valueDecimals: 2
            },
        xAxis: {
                dateTimeLabelFormats: {
					second: "%Y-%m-%d<br/>%H:%M:%S",
					minute: "%Y-%m-%d<br/>%H:%M",
					hour: "%Y-%m-%d<br/>%H:%M",
					day: "%Y<br/>%m-%d",
					week: "%Y<br/>%m-%d",
					month: "%Y-%m",
					year: "%Y"
				},
            gridLineWidth: 1 ,//纵向网格线宽度
        },
        scrollbar: {
                dateTimeLabelFormats: {
                    second: "%Y-%m-%d %H:%M:%S",
					minute: "%Y-%m-%d %H:%M",
					hour: "%Y-%m-%d %H:%M",
					day: "%Y-%m-%d",
					week: "%Y-%m-%d",
					month: "%Y-%m",
					year: "%Y"
                }
            },
        series: [{
                    name:'基准收益',
                    data:benchmark_return_list,
                    color:"#000080"
                },
                {
                    name:'回测收益',
                    data:total_returns_list,
                    color:"#8B0000"
                }]
    });
}

$(function() {

        $("#run_code").submit(function(){
            NProgress.start();
            var start_date = $("#datepicker_begin").val();
            var end_date = $("#datepicker_end").val();
            var cash = $("#principal").val();
            var content =  ace.edit("sourceCode").getValue();
            console.log(start_date);
            $.ajax({
                     type:"post",
                     dataType:"json",
                     data: {
                         'start_date': start_date,
                         'end_date': end_date,
                         'cash': cash,
                         'source_code': content,
                     },
            success: function(result, statues, xml){

                    if (result.hasOwnProperty("errtype"))
                    {
                        var errtype = result["errtype"];
                        if (errtype != "0"){
                            var strTemp = '<p style = "white-space:pre">';
                            var resultList = result['errlog'];
                            for (var temp in resultList) {
                                strTemp += resultList[temp];
                            }
                            strTemp += '<\p>';
                            console.log(strTemp);
                            showError(strTemp);
                            $("#hcsy").text("--");
                            $("#jzsy").text("--");
                            $("#hcnhsy").text("--");
                            //alert();
                            chart([], []);
                        }
                        else {
                            $("#hcsy").text((result['totalreturn']*100).toFixed(2).toString() + "%");
                            $("#jzsy").text((result['benchmark']*100).toFixed(2).toString() + "%");
                            $("#hcnhsy").text((result['annualized_returns']*100).toFixed(2).toString() + "%");
                            //alert();
                            chart(result['total_returns_list'], result['benchmark_return_list'])
                            showError("");
                        }
                    }
                    NProgress.done();
                },
            error: function(jqXHR, textStatus, errorThrown){
                    alert(jqXHR.status);
                }
            });
            return false;
        });
    });
$(function() {
    $("#source_code").submit(function(){
            var content =  ace.edit("sourceCode").getValue();
            console.log(content);
            $.ajax({
                     type:"post",
                     dataType:"json",
                     url:"",
                     data: {'source_code': content,},
            success: function(data){

                        }
            });
        return false;
    });
});

